package 每日一题;

import java.util.LinkedList;

class TreeNode {
      int val;
     TreeNode left;
     TreeNode right;
      TreeNode(int x) { val = x; }
 }
public class Codec {

    String SEP=",";
    String NULL="#";
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
       StringBuilder sb=new StringBuilder();
       serialized(root,sb);
       return sb.toString();
    }
    public void serialized(TreeNode root,StringBuilder sb){
        if(root==null){
            sb.append(NULL).append(SEP);
            return;
        }
        sb.append(root.val).append(SEP);
        serialized(root.left,sb);
        serialized(root.right,sb);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        LinkedList<String> nums=new LinkedList<>();
        for (String s:data.split(SEP)){
            nums.addLast(s);
        }
        return deserialized(nums);
    }
    public TreeNode deserialized(LinkedList<String> nums){
        if(nums.isEmpty()) return null;
        String s=nums.removeFirst();
        if(s.equals(NULL)){
            return null;
        }
        TreeNode root=new TreeNode(Integer.valueOf(s));
        root.left=deserialized(nums);
        root.right=deserialized(nums);
        return root;

    }
}
